package com.jy.fxf_phone.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jy.fxf_phone.R;
import com.jy.fxf_phone.view.FeedActivity;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by qiantao on 2016/11/22.
 * 食物掉落
 */

public class FoodDropView extends RelativeLayout {

    private static final String TAG = "FoodDropView";
    private Context mContext;
    private boolean mIsFoodClicked;
    private Subscription mSubscription;
    private int mFoodId;

    private ObjectAnimator mFallAnim;
    private AnimatorSet mClickedAnimSet;


    LinearLayout mFoodLayout;

    View mFoodBg;

    ImageView mFoodIv;

    TextView mAddTv;

    public FoodDropView(Context context) {
        this(context, null);
    }

    public FoodDropView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        View view = LayoutInflater.from(context).inflate(R.layout.view_food_drop, this);
        mFoodLayout = (LinearLayout) view.findViewById(R.id.ll_food);
        mFoodBg = view.findViewById(R.id.v_bg);
        mFoodIv = (ImageView) view.findViewById(R.id.iv_food);
        mAddTv = (TextView) view.findViewById(R.id.tv_add);

        mFoodIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                foodClicked();
            }
        });
    }

    /**
     * 开始随机时间掉落
     */
    public void startFoodDrop() {
        startFoodTimer(getRandomTime());
        Log.i(TAG, "startFoodDrop: 准备开始掉落");
    }

    /**
     * 解除subscription绑定
     */
    public void unsubscribeSubscription() {
        if (mSubscription != null) {
            mSubscription.unsubscribe();
            Log.i(TAG, "unsubscribeSubscription: 停止掉落");
        }
    }

    private void foodClicked() {
        if (mIsFoodClicked) {
            return;
        }
        mIsFoodClicked = true;
        mFallAnim.cancel();
        mAddTv.setVisibility(View.VISIBLE);
        mFoodLayout.setVisibility(View.VISIBLE);
        if (mClickedAnimSet == null) {
            mClickedAnimSet = initClickedAnim(mFoodLayout);
            mClickedAnimSet.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mFoodLayout.setVisibility(View.INVISIBLE);
                }
            });
        }

        mClickedAnimSet.start();
        SharedPreferences share = mContext.getSharedPreferences("Feed_System", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = share.edit();
        int value = share.getInt(switchFood(mFoodId), 1);
        Log.i(TAG, "foodClicked: food_" + mFoodId + ": " + value);
        editor.putInt(switchFood(mFoodId), ++value);
        editor.apply();
        Log.i(TAG, "foodClicked: food_" + mFoodId + ": " + value);
        startFoodTimer(getRandomTime());
    }

    private void startFoodTimer(int random) {
        Log.i(TAG, "startTimerTask: random: " + random);
        unsubscribeSubscription();
        mSubscription = Observable.timer(random, TimeUnit.MINUTES, AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        mFoodId = getRandomFood();
                        int drawable = mContext.getResources().getIdentifier("food_" + mFoodId,
                                "drawable", mContext.getPackageName());
                        Log.i(TAG, "drawable id: " + drawable);
                        mFoodIv.setImageResource(drawable);
                        startFallAnim();
                    }
                });
    }

    private void startFallAnim() {
        mIsFoodClicked = false;
        mFoodLayout.setVisibility(View.VISIBLE);
        mFoodLayout.setAlpha(1f);
        mFoodLayout.setScaleX(1f);
        mFoodLayout.setScaleY(1f);
        mFoodBg.setVisibility(View.VISIBLE);
        mAddTv.setVisibility(View.INVISIBLE);
        mFoodLayout.setVisibility(View.VISIBLE);
        if (mFallAnim == null) {
            mFallAnim = initFallAnim(mFoodLayout, (Activity) mContext);
            mFallAnim.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mFoodBg.setVisibility(View.INVISIBLE);
                    mFoodLayout.setVisibility(View.INVISIBLE);
                    if (!mIsFoodClicked) {
                        startFoodTimer(getRandomTime());
                    }
                }
            });
        }
        mFallAnim.start();
    }

    /**
     * 初始化降落动画
     *
     * @param v        动画作用的view
     * @param activity 动画所在的Activity
     * @return 动画
     */
    private ObjectAnimator initFallAnim(View v, Activity activity) {
        int contentHeight = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getHeight();
        int imageHeight = v.getHeight();
        ObjectAnimator animator = ObjectAnimator.ofFloat(v, "translationY", 0, contentHeight - imageHeight);
        Log.i(TAG, "onCreate: contentHeight: " + contentHeight);
        Log.i(TAG, "onCreate: imageHeight: " + imageHeight);
        animator.setInterpolator(new BounceInterpolator());
        animator.setDuration(4000);
        return animator;
    }

    /**
     * 初始化图片被点击的动画
     *
     * @param v 被点击的图片
     * @return 动画set
     */
    private AnimatorSet initClickedAnim(View v) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(v, "scaleX", 1f, 2f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(v, "scaleY", 1f, 2f);
        ObjectAnimator fadeOut = ObjectAnimator.ofFloat(v, "alpha", 1f, 0f);

        AnimatorSet set = new AnimatorSet();
        set.play(scaleX).with(scaleY).with(fadeOut);
        set.setDuration(1000);
        return set;
    }

    private int getRandomFood() {
        return new Random().nextInt(3) + 1;
    }

    private int getRandomTime() {
        return new Random().nextInt(6) + 5;
    }

    private String switchFood(int foodId) {
        String food = FeedActivity.SHARED_PREFERENCES_FOOD_01;
        switch (foodId) {
            case 1:
                food = FeedActivity.SHARED_PREFERENCES_FOOD_01;
                break;
            case 2:
                food = FeedActivity.SHARED_PREFERENCES_FOOD_02;
                break;
            case 3:
                food = FeedActivity.SHARED_PREFERENCES_FOOD_03;
                break;
        }
        return food;
    }
}
